package com.ssh.service.impl;

import com.ssh.common.MD5Utils;
import com.ssh.common.Result;
import com.ssh.entity.User;
import com.ssh.repository.UserRepository;
import com.ssh.service.UserService;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserRepository userRepository;
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Result login(User user) {

        User u = null;
        try {
            u = userRepository.getUserByAccount(user);
            if (u != null && u.getPwd().equals(user.getPwd())) {
                String token = MD5Utils.ecode(u.getAccount() + System.currentTimeMillis());
                u.setToken(token);
                try {
                   int i =  userRepository.updateByHql(u);
                   if (i <= 0){
                       throw new Exception("token更新失败！");
                   }
                } catch (HibernateException e) {
                    return Result.error("token更新失败！"+e.toString());
                }
            } else {
                return Result.error("账户名或密码错误！");
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return Result.error(e.toString());
        }
        return Result.success(u);
    }

    @Override
    public Result addUser(User user) {
        User u = null;
        try {
            u = userRepository.getUserByAccount(user);
            if (u != null) {
                return Result.error("已存在该用户，请直接登录");
            }
            Long i = userRepository.save(user);
            if (i.intValue() > 0) {
                return Result.success(user);
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return Result.error("创建账号失败");
    }
}
